import MSData
import WorkerMSAPI
import WorkerMSDB
import MSLogger
import MSDBTemplates
import WorkerPCNFirebird

import time
import os
import sys
import heartbeating

heartbeat = heartbeating.HeartbeatListener(17202)
heartbeat.start()

MSLogger.logInit('C:\\safe\\ms.fast.log', 2, True)
MSLogger.logInfo('ms driver started')
reader = WorkerMSDB.Worker('localhost', '2929', 'PGSMData', 'sa', 'safeinside')
reader.connect()

#writer = WorkerPCNFirebird.Worker('192.168.0.120:C:\\pcn6\\data\\DATA.GDB', 'SYSDBA', 'masterkey')
writer2 = WorkerPCNFirebird.Worker('192.168.0.121:C:\\pcn6\\data\\DATA.GDB', 'SYSDBA', 'masterkey')
#writer.connect()
writer2.connect()

def getObjectsFromDB(c, objs):
    objs_I1 = []

    MSDBTemplates.GET_MSObjects_FROM_CarOnline(reader.connection.cursor(), objs, 'fast')
    f = open('objects_without_INPUT1.cfg', 'r')
    list_NI1 = []
    for s in f.readlines():
        s = s.strip()
        if len(s): list_NI1.append(s)
    for o in objs:
        if str(o.objectPCNId) in list_NI1:
            o.allowINPUT1 = False
            MSLogger.logInfo('object %s:%s has NO i1' % (str(o.objectPCNId), str(o.objectMSId)))
        else:
            o.allowINPUT1 = True
            MSLogger.logInfo('object %s:%s has i1' % (str(o.objectPCNId), str(o.objectMSId)))
        objs_I1.append(o)
    return objs_I1

objects = getObjectsFromDB(reader.connection.cursor(), [])
ctr = 0

try:
    while True:
        if ctr == 6:
            objects = getObjectsFromDB(reader.connection.cursor(), objects)
            ctr = 0
        reader.readEventsPGSM(objects)
        reader.readEventsContactId(objects)
        reader.readEventsBolid(objects)
        #writer.writeEventsStatic(objects)
        writer2.writeEventsStatic(objects)
        reader.finalyze(objects)
        ctr += 1
        time.sleep(10)
except KeyboardInterrupt:
    MSLogger.logError('ms daemon stopped')
    heartbeat.stop()
    #os.unlink('C:\\safe\\ms.pid')
except Exception, err:
    shr = str(err)[0:100]
    MSLogger.logError('ms driver fatal error: %s' % (str(err)))
    heartbeat.stop()
    #os.unlink('C:\\safe\\ms.pid')
